import json
import os
import shutil
import ssl
import time
import traceback
import urllib.request

import requests

from ExportReport.ExportReport import ExportReport
from config.config import PPYY_DIR, REPORT_DIR
from libs.helper import get_token
from models.RedisModel import RedisClient5
from models.captcha import captcha
from models.orders import Orders
from models.orders_info import orders_info
from models.RedisOperation import RedisClient
from models.base import db
from models.base_db2 import db as captcha_db
from oss.alioss import AliOss

ssl._create_default_https_context = ssl._create_unverified_context

class MakeReport(object):

    def __init__(self):
        self.db = RedisClient()
        self.rdb = RedisClient5()

    def makereport(self, report):
        submit_title = report.split('$$')[0]
        url = report.split('$$')[1]
        cookies = json.loads(self.rdb.get_cookies())
        cookieDict = {}
        for cookie in cookies:
            cookieDict[cookie['name']] = cookie['value']
        file = requests.get(url, stream=True,cookies=cookieDict)
        with open(PPYY_DIR + submit_title + '.zip', 'wb') as f:
            f.write(file.content)
        orderInfo = db.query(orders_info).filter_by(submit_title=submit_title).first()
        try:
            report_model = ExportReport(PPYY_DIR + submit_title + '.zip', orderInfo.paper_number)
            report_model.create_report_directory()
            report_model.create_paper_html()
            for detail in report_model.details:
                report_model.create_index_html(str(detail['index']), detail['info'])
            info = db.query(Orders).filter_by(paper_number=orderInfo.paper_number).first()
            rateStr = report_model.ppyy_model.Orianna()
            rate = round(float(rateStr.replace('%', '')), 2)
            if rate > 5:
                rate = round(rate * 0.97, 2)
            view_info = {
                'captcha': get_token(),
                'title': info.title,
                'author': info.author,
                'char_sum': len(info.content),
                'paragraphs': len(report_model.paragraphs),
                'submit_time': info.create_datetime,
                'rate': rate
            }
            captcha_model = captcha()
            captcha_model.captcha_number = view_info['captcha']
            captcha_model.title = view_info['title']
            captcha_model.author = view_info['author']
            captcha_model.char_sum = view_info['char_sum']
            captcha_model.create_time = view_info['submit_time']
            captcha_model.similar_rate = view_info['rate']
            captcha_db.add(captcha_model)
            captcha_db.commit()
            if '\n' in info.content:
                text = info.content.split('\n')
                text_data = '<br>'.join(text)
            else:
                text_data = info.content
            report_model.create_report_html(view_info)
            report_model.create_orginal_html(text_data)
            report_model.create_pdf_html(view_info)
            report_model.zip_report()
            oss = AliOss(orderInfo.paper_number)
            oss.upload(REPORT_DIR + 'samereport_' + orderInfo.paper_number + '.zip')
            db.query(orders_info).filter(orders_info.submit_title == submit_title).update({'completed': 1, 'similar_rate': rate})
            db.commit()
            os.remove(REPORT_DIR + "samereport_" + orderInfo.paper_number + '.zip')
        except Exception as e:
            traceback.print_exc()
            try:
                shutil.rmtree(REPORT_DIR + "samereport_" + orderInfo.paper_number)
            except:
                pass
        return True

    def run(self):
        while True:
            report = self.db.get_order_number
            print(report)
            if report:
                is_launch = False
                while not is_launch:
                    is_launch = self.makereport(report)
            else:
                print('sleep 5 seconds...')
                time.sleep(3)


if __name__ == '__main__':
    make = MakeReport()
    make.run()
